<?php

class IosHelper
{
    private $pem;
    private $pass;
    
    public function __construct()
    {
       // $this->pem = dirname(__FILE__) . '/../data/' . 'ck.pem';
        $this->pem = dirname(__FILE__) . '/../data/' . 'production_ck.pem';
        $this->pass = "123123";
    }
    
    public function pushToSingle($deviceToken, $title,$paperId)
    {
        $body = array("aps" => array("alert" => $title,"badge" =>0,"sound"=>'default'),"pid"=>$paperId);  //推送方式，包含内容和声音
        $ctx = stream_context_create();
        stream_context_set_option($ctx,"ssl","local_cert",$this->pem);
        stream_context_set_option($ctx, 'ssl', 'passphrase', $this->pass);
        //此处有两个服务器需要选择，如果是开发测试用，选择第二名sandbox的服务器并使用Dev的pem证书，如果是正是发布，使用Product的pem并选用正式的服务器
        //$fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        $fp = stream_socket_client("ssl://gateway.sandbox.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if (!$fp) {
            echo "Failed to connect $err $errstr";
            return "error";
        }
        $payload = json_encode($body);
        $msg = chr(0) . pack("n",32) . pack("H*", str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
        fwrite($fp, $msg);
        fclose($fp);
        return "ok";
    }

}